package ar.com.cooker.spider.ut;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;

import ar.com.cooker.spider.SpiderException;

public class ConnectionProxy {

	
	private static ConnectionProxy instance = null;
	
	private int proxyPort =  80;
    private String proxyHost = null;
    private Proxy proxy = null;
    private boolean useProxy = false;
	
	private ConnectionProxy() throws SpiderException{
		
		try{			
			this.proxyPort = Integer.parseInt(PropertyManager.getInstance().getProxyPort());
			this.proxyHost = PropertyManager.getInstance().getProxyHost();
			this.useProxy = PropertyManager.getInstance().getUseProxy();
		}catch(Exception e){
			throw new SpiderException("Imposible obtener alguna de las propiedades necesarias para cargar la p�gina\n"+
					 "en clase: "+this.getClass().toString()+". motivo: "+e.getCause(),e);
		}
		if(useProxy){
			proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
		}
	}
	
	public static ConnectionProxy getInstance() throws SpiderException{
		if(instance==null) 
			instance = new ConnectionProxy();
		return instance;
	}
	

		
	public BufferedReader getBRPageContent(String page) throws SpiderException{
		URL url=null;
		try {
			url = new URL(page);
		} catch (MalformedURLException e3) {
			throw new SpiderException("Imposible crear URL, en clase: "+this.getClass().toString()+". motivo: "+e3.getCause(),e3);
		}
		HttpURLConnection uc = null;
		try {
			if(this.useProxy){
				uc = (HttpURLConnection)url.openConnection(proxy);
			}else{
				uc = (HttpURLConnection)url.openConnection();
			}
		} catch (IOException e2) {		
			if(this.useProxy){
				throw new SpiderException("Imposible abrir URL utilizando el proxy, en clase: "+this.getClass().toString()+". motivo: "+e2.getCause(),e2);
			}else{
				throw new SpiderException("Imposible abrir URL (sin proxy), en clase: "+this.getClass().toString()+". motivo: "+e2.getCause(),e2);
			}
		}
		try {
			uc.connect();
		} catch (IOException e1) {
			if(this.useProxy){
				throw new SpiderException("Imposible abrir HttpURLConnection utilizando el proxy, en clase: "+this.getClass().toString()+". motivo: "+e1.getCause(),e1);
			}else{
				throw new SpiderException("Imposible abrir HttpURLConnection (sin proxy), en clase: "+this.getClass().toString()+". motivo: "+e1.getCause(),e1);				
			}
		}		
		BufferedReader in = null;		
		try {			
			in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
		} catch (IOException e1) {
			throw new SpiderException("Imposible leer contenido descargado en clase: "+this.getClass().toString()+". motivo: "+e1.getCause(),e1);
		}
		return in;
	}
}
